﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace NEWS.Admin
{
    public partial class NewsHouses : System.Web.UI.Page
    {
        private static string mode = null;
        private static string modeapprove = null;
        private static NewsHouseBO newshBO;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                modeapprove = Request.QueryString["approve"];
                GridView1.Columns[1].Visible = false;
                if (modeapprove == "true")
                {
                    lblview_approve.Text = "Duyệt tin nhà đất";
                    pn_view.Visible = false;
                    pn_approve.Visible = true;
                    GridView1.Columns[2].Visible = false;                    
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(true, false, false);
                    GridView1.DataBind();
                    mode = Request.QueryString["type"];
                    if (mode == "update")
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Đã kích hoạt tin.";
                    }
                }
                else
                {
                    GridView1.Columns[8].Visible = false;
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList();
                    GridView1.DataBind();
                    mode = Request.QueryString["type"];
                    if (mode == "insert")
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Đăng tin thành công.";
                    }
                    else if (mode == "update")
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Cập nhật thành công.";
                    }
                }
            }
        }

        protected void btndangtin_Click(object sender, EventArgs e)
        {
            Response.Redirect("EditNewsHouses.aspx");
        }

        protected void btnxoatin_Click(object sender, EventArgs e)
        {
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int newsid = Convert.ToInt32(gvRow.Cells[3].Text);
                        NewsHouseBOList.Delete_ByKey(newsid);
                        newshBO = NewsHouseBO.GetNewsHouseBO(newsid);
                        if (newshBO.UrlImage != "")
                        {
                            var array_listImage = newshBO.UrlImage.Split('/');
                            foreach (var detail in array_listImage)
                            {
                                deleteExitsImage(detail);
                            }
                        }
                        NewsHouseBO.DeleteNewsHouseBO(newsid);
                    }
                    catch
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Xoá thất bại.";
                        dlkieuxem_SelectedIndexChanged(sender, e);
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin cần xóa!!!')", true);
                return;
            }
            else
            {
                dlkieuxem_SelectedIndexChanged(sender, e);
                pn_result.Visible = true;
                lblthongbao.Text = "Xoá thành công.";
            }            
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("~/TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Xem2")
            {
                GridViewRow selectrow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                string Title = ((LinkButton)(((Control)e.CommandSource).Parent.Parent).FindControl("lbttitle")).Text;
                Response.Redirect("../TinNhaDatChiTiet.aspx?id=" + selectrow.Cells[3].Text);
            }
            else if (e.CommandName == "delete")
            {
                //GridViewRow selectrow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                //int idnewshouse = Convert.ToInt32(selectrow.Cells[3].Text);
                ////kiem tra tin dang duoc dang va tin la tin vip
                //try
                //{
                //    ImageButton IB = ((ImageButton)(((Control)e.CommandSource).Parent.Parent).FindControl("IBdelete"));
                //    IB.Attributes.Add("onclick",
                //       "return confirm('Are you sure you want to delete "
                //        + idnewshouse + "?');");
                //}
                //catch { }

            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(GridView1.SelectedRow.Cells[3].Text);            
            if (modeapprove == "true")
                Response.Redirect("EditNewsHouses.aspx?id=" + GridView1.SelectedRow.Cells[3].Text + "&approve=true");
            else if (NewsHouseBO.GetNewsHouseBO(id).UserName != Session["UserNameAdmin"].ToString())
            {
                Response.Redirect("EditNewsHouses.aspx?id=" + GridView1.SelectedRow.Cells[3].Text + "&view=true");
            }
            else
            {
                Response.Redirect("EditNewsHouses.aspx?id=" + GridView1.SelectedRow.Cells[3].Text);
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    var UrlImage = (Label)e.Row.Cells[7].FindControl("lblimage");
                    //string imageString = "img/noimage.gif";
                    string imageString;
                    if (UrlImage.Text != "")
                    {
                        var arrayimage = UrlImage.Text.Split('/');
                        var pathFileImage = Server.MapPath("~/TotalUpload/ImagesTotal/" + arrayimage[0]);
                        if (File.Exists(pathFileImage))
                        {
                            imageString = "/TotalUpload/ImagesTotal/" + arrayimage[0];
                        }
                        else imageString = "/TotalUpload/ImagesTotal/noimage.gif";
                    }
                    else imageString = "/TotalUpload/ImagesTotal/noimage.gif";

                    var LinkButtonTitle = (LinkButton)e.Row.Cells[4].FindControl("lbttitle");
                    var labelsurfaceArea = (Label)e.Row.Cells[7].FindControl("lbldientich");
                    var labelsurfaceAreaHeight = (Label)e.Row.Cells[7].FindControl("lbldientichdai");
                    string dientich = "";
                    if (labelsurfaceArea.Text == "-1")
                    {
                        dientich = "Chưa có";
                    }
                    else if (labelsurfaceArea.Text == labelsurfaceAreaHeight.Text)
                    {
                        dientich = labelsurfaceArea.Text + " " + "m<sup>2</sup>";
                    }
                    else
                    {
                        dientich = labelsurfaceArea.Text + " x " + labelsurfaceAreaHeight.Text + " (m x m) ";
                    }
                    var labelPrice = (Label)e.Row.Cells[7].FindControl("lblgia");
                    var labelLoaitien = (Label)e.Row.Cells[7].FindControl("lblloaitien");
                    var cbsupm = (CheckBox)e.Row.Cells[7].FindControl("cbSup");
                    string issupm = "";
                    if (cbsupm.Checked == true) issupm = "/m<sup>2</sup>";
                    string price_loaitien_sup = "";
                    if (Convert.ToInt32(labelPrice.Text) == -1)
                    {
                        price_loaitien_sup = "Chưa có giá";
                    }
                    else price_loaitien_sup = labelPrice.Text + "  " + labelLoaitien.Text + "  " + issupm;

                    var labelAreaDetail = (Label)e.Row.Cells[7].FindControl("lblvitri");
                    var hiddenFielContent = (Label)e.Row.Cells[7].FindControl("lblmota");
                    var hiddenFielContentShort = hiddenFielContent.Text.Length > 20
                                                     ? hiddenFielContent.Text.Substring(0, 20) + "..."
                                                     : hiddenFielContent.Text;
                    string strHtml = "<table><tr><td rowspan=4 class=\"tootipadmin\"><img width=\"130\" height=\"130\"  src=\"" + imageString + "\"/></td>";
                    strHtml += "<td style=\"padding-right:5px;\"><b>Diện tích:</b></td><td>" + dientich + "</td></tr>";
                    strHtml += "<tr><td><b>Gía:</b></td><td style=\"color:red;\">" + price_loaitien_sup + "</td></tr>";
                    strHtml += "<tr><td><b>Vị trí:</b></td><td>" + labelAreaDetail.Text + "</td></tr>";
                    strHtml += "<tr><td><b>Hướng:</b></td><td>" + hiddenFielContentShort + "</td></tr></table>";

                    LinkButtonTitle.Attributes.Add("onMouseover", "ddrivetip('" + strHtml + "', 360);");
                    LinkButtonTitle.Attributes.Add("onMouseout", "hideddrivetip();");
                    LinkButtonTitle.Attributes.Add("onMouseover", "ddrivetip('" + strHtml + "', 360);");
                    LinkButtonTitle.Attributes.Add("onMouseout", "hideddrivetip();");

                    string strScript = "SelectDeSelectHeader(" + ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).ClientID + ");";
                    ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Attributes.Add("onclick", strScript);
                }
            }
            catch { }
        }

        protected void dlkieuxem_SelectedIndexChanged(object sender, EventArgs e)
        {
            pn_result.Visible = false;
            if (dlkieuxem.SelectedValue == "tatca")
            {
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList();
                GridView1.DataBind();
            }
            else if (dlkieuxem.SelectedValue == "hethan")
            {
                NewsHouseBOList.KiemTra_TinHetHan();
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByEx_ByIsAdver(true);
                GridView1.DataBind();
            }
            else
            {
                NewsHouseBOList.KiemTra_TinTraPhiHetHan();
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByEx_ByIsAdver(false);
                GridView1.DataBind();
            }
        }

        protected void dlviewapprove_SelectedIndexChanged(object sender, EventArgs e)
        {
            pn_result.Visible = false;
            if (dlviewapprove.SelectedValue == "quangcao")
            {
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(true,false,false);
                GridView1.DataBind();
            }
            else if (dlviewapprove.SelectedValue == "mienphi")
            {
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(false,true,false);
                GridView1.DataBind();
            }
            else
            {
                GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(false,false,true);
                GridView1.DataBind();
            }
        }

        protected void btnapprove_Click(object sender, EventArgs e)
        {            
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("cbapprove");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int newshouseid = Convert.ToInt32(gvRow.Cells[3].Text);
                        newshBO = NewsHouseBO.GetNewsHouseBO(newshouseid);
                        newshBO.IsActive = true;
                        newshBO.Save();
                    }
                    catch
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Duyệt tin thất bại.";
                        dlviewapprove_SelectedIndexChanged(sender, e);
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin cần duyệt !!!')", true);
                return;
            }
            else
            {
                dlviewapprove_SelectedIndexChanged(sender, e);
                pn_result.Visible = true;
                lblthongbao.Text = "Đã duyệt tin(Tin đã được phép đăng).";
            }           
        }

        protected void btnapproveall_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                try
                {
                    int newshouseid = Convert.ToInt32(gvRow.Cells[3].Text);
                    newshBO = NewsHouseBO.GetNewsHouseBO(newshouseid);
                    newshBO.IsActive = true;
                    newshBO.Save();
                    dlviewapprove_SelectedIndexChanged(sender, e);
                    pn_result.Visible = true;
                    lblthongbao.Text = "Đã duyệt tin(Tin đã được phép đăng).";
                }
                catch
                {
                    dlviewapprove_SelectedIndexChanged(sender, e);
                    pn_result.Visible = true;
                    lblthongbao.Text = "Duyệt tin thất bại.";
                }
            }                   
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        public void BindGrid()
        {
            if (modeapprove == "true")
            {
                if (dlviewapprove.SelectedValue == "quangcao")
                {
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(true, false, false);
                    GridView1.DataBind();
                }
                else if (dlviewapprove.SelectedValue == "mienphi")
                {
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(false, true, false);
                    GridView1.DataBind();
                }
                else
                {
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByApprove(false, false, true);
                    GridView1.DataBind();
                }
            }
            else
            {
                if (dlkieuxem.SelectedValue == "tatca")
                {
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList();
                    GridView1.DataBind();
                }
                else if (dlkieuxem.SelectedValue == "hethan")
                {
                    NewsHouseBOList.KiemTra_TinHetHan();
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByEx_ByIsAdver(true);
                    GridView1.DataBind();
                }
                else
                {
                    NewsHouseBOList.KiemTra_TinTraPhiHetHan();
                    GridView1.DataSource = NewsHouseBOList.GetAllNewsHousesBOList_ByEx_ByIsAdver(false);
                    GridView1.DataBind();
                }
            }
        }

        protected void lbtketthuc_Click(object sender, EventArgs e)
        {
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int newshouseid = Convert.ToInt32(gvRow.Cells[3].Text);
                        newshBO = NewsHouseBO.GetNewsHouseBO(newshouseid);
                        newshBO.IsActive = false;
                        newshBO.Save();
                    }
                    catch
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Kết thúc đăng tin thất bại.";
                        dlkieuxem_SelectedIndexChanged(sender, e);
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin cần kết thúc đăng tin !!!')", true);
                return;
            }
            else
            {
                dlkieuxem_SelectedIndexChanged(sender, e);
                pn_result.Visible = true;
                lblthongbao.Text = "Đã kết thúc đăng tin của các tin được chọn.";
            }
        }
    }
}